package com.company.project.common.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

@Slf4j
public class RSAEncrypt {
    /**
     * 字节数据转字符串专用集合
     */
    private static final char[] HEX_CHAR = { '0', '1', '2', '3', '4', '5', '6',
            '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

    /**
     * 随机生成密钥对
     */
    public static void genKeyPair(String filePath) {
        // KeyPairGenerator类用于生成公钥和私钥对，基于RSA算法生成对象
        KeyPairGenerator keyPairGen = null;
        try {
            keyPairGen = KeyPairGenerator.getInstance("RSA");
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // 初始化密钥对生成器，密钥大小为96-1024位
        keyPairGen.initialize(1024,new SecureRandom());
        // 生成一个密钥对，保存在keyPair中
        KeyPair keyPair = keyPairGen.generateKeyPair();
        // 得到私钥
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        // 得到公钥
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        try {
            // 得到公钥字符串
            String publicKeyString =RSAEncrypt.encode(publicKey.getEncoded());
//       // 得到私钥字符串
            String privateKeyString = RSAEncrypt.encode(privateKey.getEncoded());
            // 将密钥对写入到文件
            FileWriter pubfw = new FileWriter(filePath + "/publicKey.keystore");
            FileWriter prifw = new FileWriter(filePath + "/privateKey.keystore");
            BufferedWriter pubbw = new BufferedWriter(pubfw);
            BufferedWriter pribw = new BufferedWriter(prifw);
            pubbw.write(publicKeyString);
            pribw.write(privateKeyString);
            pubbw.flush();
            pubbw.close();
            pubfw.close();
            pribw.flush();
            pribw.close();
            prifw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 从文件中输入流中加载公钥
     *
     * @param in
     *            公钥输入流
     * @throws Exception
     *             加载公钥时产生的异常
     */
    public static String loadPublicKeyByFile(String path) throws Exception {
        try {
            BufferedReader br = new BufferedReader(new FileReader(path
                    + "/publicKey.keystore"));
            String readLine = null;
            StringBuilder sb = new StringBuilder();
            while ((readLine = br.readLine()) != null) {
                sb.append(readLine);
            }
            br.close();
            return sb.toString();
        } catch (IOException e) {
            throw new Exception("公钥数据流读取错误");
        } catch (NullPointerException e) {
            throw new Exception("公钥输入流为空");
        }
    }

    /**
     * 从字符串中加载公钥
     *
     * @param publicKeyStr
     *            公钥数据字符串
     * @throws Exception
     *             加载公钥时产生的异常
     */
    public static RSAPublicKey loadPublicKeyByStr(String publicKeyStr)
            throws Exception {
        try {
            byte[] buffer = RSAEncrypt.decode(publicKeyStr);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
            return (RSAPublicKey) keyFactory.generatePublic(keySpec);
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此算法");
        } catch (InvalidKeySpecException e) {
            throw new Exception("公钥非法");
        } catch (NullPointerException e) {
            throw new Exception("公钥数据为空");
        }
    }

    /**
     * 从文件中加载私钥
     *
     * @param keyFileName
     *            私钥文件名
     * @return 是否成功
     * @throws Exception
     */
    public static String loadPrivateKeyByFile(String path) throws Exception {
        try {
            BufferedReader br = new BufferedReader(new FileReader(path
                    + "/privateKey.keystore"));
            String readLine = null;
            StringBuilder sb = new StringBuilder();
            while ((readLine = br.readLine()) != null) {
                sb.append(readLine);
            }
            br.close();
            return sb.toString();
        } catch (IOException e) {
            throw new Exception("私钥数据读取错误");
        } catch (NullPointerException e) {
            throw new Exception("私钥输入流为空");
        }
    }

    public static RSAPrivateKey loadPrivateKeyByStr(String privateKeyStr)
            throws Exception {
        try {
            byte[] buffer = RSAEncrypt.decode(privateKeyStr);
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此算法");
        } catch (InvalidKeySpecException e) {
            throw new Exception("私钥非法");
        } catch (NullPointerException e) {
            throw new Exception("私钥数据为空");
        }
    }

    /**
     * 公钥加密过程
     *
     * @param publicKey
     *            公钥
     * @param plainTextData
     *            明文数据
     * @return
     * @throws Exception
     *             加密过程中的异常信息
     */
    public static byte[] encrypt(RSAPublicKey publicKey, byte[] plainTextData)
            throws Exception {
        if (publicKey == null) {
            throw new Exception("加密公钥为空, 请设置");
        }
        Cipher cipher = null;
        try {
            // 使用默认RSA
            cipher = Cipher.getInstance("RSA");
            // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] output = cipher.doFinal(plainTextData);
            return output;
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此加密算法");
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
            return null;
        } catch (InvalidKeyException e) {
            throw new Exception("加密公钥非法,请检查");
        } catch (IllegalBlockSizeException e) {
            throw new Exception("明文长度非法");
        } catch (BadPaddingException e) {
            throw new Exception("明文数据已损坏");
        }
    }


    /**
     * 私钥加密过程
     *
     * @param privateKey
     *            私钥
     * @param plainTextData
     *            明文数据
     * @return
     * @throws Exception
     *             加密过程中的异常信息
     */
    public static byte[] encrypt(RSAPrivateKey privateKey, byte[] plainTextData)
            throws Exception {
        if (privateKey == null) {
            throw new Exception("加密私钥为空, 请设置");
        }
        Cipher cipher = null;
        try {
            // 使用默认RSA
            cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, privateKey);
            byte[] output = cipher.doFinal(plainTextData);
            return output;
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此加密算法");
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
            return null;
        } catch (InvalidKeyException e) {
            throw new Exception("加密私钥非法,请检查");
        } catch (IllegalBlockSizeException e) {
            throw new Exception("明文长度非法");
        } catch (BadPaddingException e) {
            throw new Exception("明文数据已损坏");
        }
    }



    /**
     * 私钥解密过程
     *
     * @param privateKey
     *            私钥
     * @param cipherData
     *            密文数据
     * @return 明文
     * @throws Exception
     *             解密过程中的异常信息
     */
    public static byte[] decrypt(RSAPrivateKey privateKey, byte[] cipherData)
            throws Exception {
        if (privateKey == null) {
            throw new Exception("解密私钥为空, 请设置");
        }
        Cipher cipher = null;
        try {
            // 使用默认RSA
            cipher = Cipher.getInstance("RSA");
            // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] output = cipher.doFinal(cipherData);
            return output;
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此解密算法");
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
            return null;
        } catch (InvalidKeyException e) {
            throw new Exception("解密私钥非法,请检查");
        } catch (IllegalBlockSizeException e) {
            throw new Exception("密文长度非法");
        } catch (BadPaddingException e) {
            throw new Exception("密文数据已损坏");
        }
    }



    /**
     * 公钥解密过程
     *
     * @param publicKey
     *            公钥
     * @param cipherData
     *            密文数据
     * @return 明文
     * @throws Exception
     *             解密过程中的异常信息
     */
    public static byte[] decrypt(RSAPublicKey publicKey, byte[] cipherData)
            throws Exception {
        if (publicKey == null) {
            throw new Exception("解密公钥为空, 请设置");
        }
        Cipher cipher = null;
        try {
            // 使用默认RSA
            cipher = Cipher.getInstance("RSA");
            // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());
            cipher.init(Cipher.DECRYPT_MODE, publicKey);
            byte[] output = cipher.doFinal(cipherData);
            return output;
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此解密算法");
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
            return null;
        } catch (InvalidKeyException e) {
            throw new Exception("解密公钥非法,请检查");
        } catch (IllegalBlockSizeException e) {
            throw new Exception("密文长度非法");
        } catch (BadPaddingException e) {
            throw new Exception("密文数据已损坏");
        }
    }


    /**
     * 公钥加密
     * @param publicKeyStr
     * @param data 加密字符串
     * @return String 密文数据
     * @throws Exception
     */
    public static String encryptForPuKey(String publicKeyStr, String data) throws Exception{
        RSAPublicKey publicKey=RSAEncrypt.loadPublicKeyByStr(publicKeyStr);
        byte[] cipherData=encrypt(publicKey,data.getBytes());
        String cipher=RSAEncrypt.encode(cipherData);
        return cipher;
    }
    /**
     * 私钥加密
     * @param privateKeyStr 私钥
     * @param data 加密字符串
     * @return String 密文数据
     * @throws Exception
     */
    public static String encryptForPrKey(String privateKeyStr, String data) throws Exception{
        RSAPrivateKey privateKey=RSAEncrypt.loadPrivateKeyByStr(privateKeyStr);
        byte[] cipherData=encrypt(privateKey,data.getBytes());
        String cipher=RSAEncrypt.encode(cipherData);
        return cipher;
    }

    /**
     * 私钥解密方法
     * @param privateKey 私钥
     * @param plainTextData 密文
     * @return String 明文
     * @throws Exception
     */
    public static String decryptForPrKey(String privateKey, String plainTextData) throws Exception{
        byte[] res=RSAEncrypt.decrypt(RSAEncrypt.loadPrivateKeyByStr(privateKey), RSAEncrypt.decode(plainTextData));
        String restr=new String(res);
        return restr;
    }

    /**
     * 公钥解密方法
     * @param publicKey
     * @param plainTextData 密文
     * @return 明文
     * @throws Exception
     */
    public static String decryptForPuKey(String publicKey, String plainTextData) throws Exception{
        byte[] res=RSAEncrypt.decrypt(RSAEncrypt.loadPublicKeyByStr(publicKey), RSAEncrypt.decode(plainTextData));
        String restr=new String(res);
        return restr;
    }

    /**
     * base64编码
     */

    public static String encode(byte[]  str) {
        String encStr=null;
        try {
            encStr = Base64.getEncoder().encodeToString(str);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return encStr;

    }

    public static String getEncoder(String str) {
        String encStr=null;
        try {
            encStr = Base64.getEncoder().encodeToString(str.getBytes("utf-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return encStr;

    }

    /**
     * base64解码
     */
    public static String getDecoder(String str) {

        byte[] asBytes = Base64.getDecoder().decode(str);
        String sr=null;
        try {
            sr=new String(asBytes, "utf-8");
        } catch (Exception e) {

            e.printStackTrace();
        }
        return sr;
    }

    /**
     * base64解码
     */
    public static  byte[]  decode(String str) {

        byte[] asBytes = Base64.getDecoder().decode(str);
        String sr=null;
        try {
        } catch (Exception e) {

            e.printStackTrace();
        }
        return  asBytes;
    }

    /**
     * 字节数据转十六进制字符串
     *
     * @param data
     *            输入数据
     * @return 十六进制内容
     */
    public static String byteArrayToString(byte[] data) {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < data.length; i++) {
            // 取出字节的高四位 作为索引得到相应的十六进制标识符 注意无符号右移
            stringBuilder.append(HEX_CHAR[(data[i] & 0xf0) >>> 4]);
            // 取出字节的低四位 作为索引得到相应的十六进制标识符
            stringBuilder.append(HEX_CHAR[(data[i] & 0x0f)]);
            if (i < data.length - 1) {
                stringBuilder.append(' ');
            }
        }
        return stringBuilder.toString();
    }


    public static void main(String[] args) {
        //1生成公私钥
        //RSAEncrypt.genKeyPair("D:\\");
        try {
            String result = decryptForPrKey("MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCVZ7d1HqMntEGiWmpVfi8aiSi+2tdVcessL1vHGk3sFB0MNokfQYhkykEztrqprcxjKQrP1XJMeao8Ky1d/6MogNEBYK/hzTn4p9TgXv0Gmrt83xSEtdNBJbVqpJJLyZ5iM94lUdOq+FiICtaq7+C5/sxnOv9c2l6za2kYKIzqMdJc4MD8azqgTJPnuY27y9mTJ8dlzbD0Msx2YqlQ7e61Hs2+jdfSZopzR+OQRIFh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Hl4u6pEXd8vAGO0cVXZSpWfW/hKPYX0g0KvlQcSkRbzHC5CP8MBmEtrqX17sW4D2e5w9hnXu/4K+wc8GsFlf72hm1D1CZxcgQKBgGjT3vA4n9LRJ+ZXD946EzECxeWuDS1+B34hw9EKJvriaq23gWo3z41hI3ljRV+qE0ENrfz1MMAEr9djbhzPHmjixPyeRemKlpXdKADtphek5jRil5RvZ1W4o9DGmo70Uv3gdQXyA05wPhBVX/jofhWzcjBDuomObD+w9jEuMLzX",
                    "guXmK1amyUxLDU1nWCDm+xVjeDJ/BVrvkb4Zg24ENcUXU6F+pvunbDP3gl40qqEGTCyCIy+b3tWwPpRNyUA8LXCS6HKHM70Yp41x3ONwNp4B8UvllAQq5+WCaf06Eq+AuA0be6zLhIWB0/zqPjM/TtBwxAp0uJ1kx5D1/Rq62LFZKXfl2MMFvDiNrllVGJSIBU297xIbqN3zdmytSt3KytcXR7dDJ2K9H/yTi5usQH0eB9bAzG5kgFOl8SIOUvFY5/NXSrS6V15m2gW2BOtKUBFD9+6uXTTgcB3Bj1cUqpzZi3Ktct8nXOjSlcQh6Nb4D4xrsm9cmytMO4GQctirjA==");

            log.info("解密结果："+result);
        }catch (Exception e){
            log.error("解密异常：",e);
        }

    }
}
